const bookModel = require('../models/books.model.js');
const fs = require('fs');
const path = require('path');

module.exports = {
    /**
     * 添加二手书
     */
    async addBook(formData) {
        let book_id = Date.now();
        let result = await bookModel.addBook({
            book_id,
            name: formData.name || '',
            tag: formData.tag || '',
            price: formData.price || '',
            description: formData.description || '',
            picture_directory: formData.picture_directory || '',
            position: formData.position || '',
            user_id: formData.user_id || '',
            state: formData.state || '',
        });
        return result;
    },
    /**
     * 通过ID获取二手书信息
     * 
     */
    async getInfoById(formData) {
        let result = await bookModel.getInfoById(formData);
        return result;
    },
    /**
     * 读取文件夹
     */
    readDir(p, picture_directory) {
        let res = [];
        let lists = fs.readdirSync(p);
        for (let list of lists) {
            let filePath = path.join(p, list);
            let stat = fs.statSync(filePath);
            if (stat && stat.isDirectory()) {
                res = res.concat(readDir(filePath, picture_directory));
            } else {
                res.push(`/books/${picture_directory}/` + list);
            }
        }
        return res;
    },
    /**
     * 查看二手书是否上传过图片
     */
    async getPic(formData) {
        let result = await bookModel.getPic(formData);
        return result;
    },
    /**
     * 二手书信息修改
     */
    async modifyBookInfo(condition, data, folderName) {
        let result = await bookModel.modifyBookInfo({
            condition,
            info: {
                name: data.name || '',
                tag: data.tag || '',
                price: data.price || 0,
                description: data.description || '',
                picture_directory: folderName,
                position: data.position || '',
                state: data.state || '',
                user_id: data.user_id
            }
        });
        return result;
    },
    /**
     * 添加二手书评论
     */
    async addEvaluate(formData) {
        let result = await bookModel.addEvaluate(formData);
        return result;
    },
    /**
     * 二手书评论获取
     */
    async getEvaluate(formData) {
        let result = await bookModel.getEvaluate(formData);
        return result;
    },
    /**
     * 二手书搜索
     */
    async searchBooks(formData) {
        let result = await bookModel.searchBooks(formData);
        return result;
    },
    /**
     * 二手书 今日推荐
     */
    async recommend() {
        let result = await bookModel.recommend();
        return result;
    }
}